import os
import datetime
import math


def save_result(acc, ylabel, args):
    data = {}
    for i in range(len(acc)):
        data['acc{}'.format(i+1)] = acc[i]
    # data = {'base' :data}

    path = './output/new/{}'.format(args.noniid_case)

    if args.noniid_case != 5:
        # file = '{}_{}_{}_d{}_{}_{}_10_groups_1_blocks_{}_{}_lr_{}_{}.txt'.format(args.dataset,args.iid, args.noniid_case,args.data_beta,args.algorithm, args.model,
        #                                                         ylabel, args.epochs, args.lr, datetime.datetime.now().strftime(
        #         "%Y_%m_%d_%H_%M_%S"))
        file='limit_{}_{}_{}_{}_{}_d{}_{}_{}_{}_lr_{}_id{}_id{}_block3_client_442_limit_ratio{}-{}-{}_layers_2_{}'.format(args.dataset,args.num_users,args.frac,args.iid, args.noniid_case,args.data_beta,args.algorithm, args.model,
                                                                 args.epochs, args.lr, args.num_id1, args.num_id2,args.client1_frac,args.client2_frac,args.client3_frac,datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S"))
    else:
        path += '/{}'.format(args.data_beta)
        # file = '{}_{}_{}_{}_{}_{}_{}_lr_{}_{}.txt'.format(args.dataset,args.iid,args.noniid_case, args.algorithm,args.model,
        #                                                            ylabel, args.epochs, args.lr,
        #                                                            datetime.datetime.now().strftime(
        #                                                                "%Y_%m_%d_%H_%M_%S"))
        file='limit_{}_{}_{}_{}_{}_d{}_{}_{}_{}_lr_{}_id{}_id{}_block3_client_442_limit_ratio{}-{}-{}_layers_2_{}'.format(args.dataset,args.num_users,args.frac,args.iid, args.noniid_case,args.data_beta,args.algorithm, args.model,
                                                                 args.epochs, args.lr, args.num_id1, args.num_id2,args.client1_frac,args.client2_frac,args.client3_frac,datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S"))

    if not os.path.exists(path):
        os.makedirs(path)
    with open(os.path.join(path,file), 'a') as f:
        for label in data:
            f.write(label)
            f.write(' ')
            for item in data[label]:
                item1 = str(item)
                f.write(item1)
                f.write(' ')
            f.write('\n')

        f.write('avg and var:\n')
        for label in data:
            f.write(label)
            f.write(' ')
            avg,var = compute_avg(data[label])
            f.write(str(avg))
            f.write('+')
            f.write(str(var))
            f.write('\n')
    print('save finished')
    f.close()

def compute_avg(acc):
    length = 10
    temp = 0
    max = 0
    index = 0
    if len(acc) < length :
        return 0.0,0.0
    for i in range(len(acc)-length):
        temp = 0
        for j in range(i,i+length):
            temp = temp+float(acc[j])
        if temp > max:
            max = temp
            index = i
    avg = max/length
    var = 0
    for x in range(index,index+length):
        var = var + (float(acc[x]) - avg) ** 2
    var = math.sqrt(var/(length))
    return  avg,var